package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

/**
 * 用户操作
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        /*System.out.println(user);*/
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    //获取菜单信息
    @RequestMapping("/getMenuInfo")
    public Result getMenuInfo(){
        try {
            List<Menu> list = userService.getMenuInfo();
            return new Result(true,MessageConstant.GET_MENU_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MENU_FAIL);
        }
    }

    //根据角色id获取菜单数据
    @RequestMapping("/getUserMenuInfo")
    public Result getMenuInfoByRole(){
        //获取角色权限
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null){
            //获取角色的角色id
            String username = user.getUsername();
            Integer rid = userService.findRoleIDByUserName(username);

            //根据id获取菜单信息
            try {
                List<Menu> list = userService.getMenuInfoByRole(rid);
                return new Result(true,MessageConstant.GET_MENU_SUCCESS,list);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.GET_MENU_FAIL);
            }
        }

        return new Result(false,MessageConstant.GET_MENU_FAIL);

    }



}
